<?php

namespace App\Http\Controllers;

use App\bNumber;
use App\CompanySetting;
use App\premiumRatio;
use App\Rate;
use App\User;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Auth;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\Schema;
use Illuminate\Support\Facades\Storage;
use Maatwebsite\Excel\Facades\Excel;

class IndexController extends Controller
{
    //
    public function login(Request $request){
       return view('Home.login');
    }
    public function loginForm(Request $request){
        if(!$request->name){
            return back()->withErrors(['请输入用户名！'])->withInput();
        }
        if(!$request->password){
            return back()->withErrors(['请输入密码！'])->withInput();
        }
        $state = $this->version_user($request->all());
        if($state){
            $user = User::where('name','=',$request->name)->orWhere('email','=',$request->name)->first();
            $this->setCookie('login-cookie',time(),7200);
            $request->session()->put('user',$user);
            return redirect('/admin/index');
        }else{
            return back()->withErrors(['用户名密码错误！'])->withInput();
        }
    }
    public function index(Request $request){
//        dd(session('user'));
        return view('Home.Index');
    }
    public function companySettingsList(Request $request){
        $list = CompanySetting::where('state','=',1)->get();
        $data['list'] = $list;
        return view('Home.companySettingsList',compact('data',$data));
    }
    public function companySettingsAdd(Request $request){
        $data = [];
        $model = [];
        if($request->id){
            $model = CompanySetting::find($request->id);
        }
        $data['model'] = $model;
        return view('Home.companySettingsAdd',compact('data',$data));
    }
    public function companySettingsSave(Request $request){
            $arr = $request->all();
            $columns = Schema::getColumnListing('company_settings');
            $sql = new CompanySetting;
            if($request->id){
                $sql = CompanySetting::find($request->id);
            }
            foreach ($arr as $key=>$item){
                if(in_array($key,$columns)){
                    $sql->$key = $item;
                }
            }
            $ret = $sql->save();
            if($ret){
                return redirect('/admin/companySettingsList');
            }else{
                return back()->withErrors(['保存失败！'])->withInput();
            }
    }
    public function excelExplode(Request $request){
        $list = CompanySetting::where('state','=',1)->get();
        $data['list'] = $list;
        return view('Home.excelExplode',compact('data',$data));
    }
    public function excelSave(Request $request){
        $file = $request->file;//接受文件路径
//        return json_encode($file->isValid());
        if ($file && $file->isValid()) {
            // 获取文件相关信息
            $originalName = $file->getClientOriginalName(); // 文件原名
            $ext = $file->getClientOriginalExtension();     // 扩展名
            if($ext!='xlsx' && $ext!='xls'){
                return $this->responseAjax('fail','请上传excel文件');
            }

            $filename = $originalName;
            if(Storage::disk('public')->exists('uploads/'.$filename)) {
//                dd(Storage::disk('public'));
//                return $this->responseAjax('fail','文件已上传');
            }else{
                Storage::disk('public')->makeDirectory('uploads');
                Storage::disk('public')->putFileAs('uploads',$file,$filename);
            }
//            $premiumRatio = new premiumRatio;
            $path = 'Storage/app/public/uploads/'.$filename;
            $batch = new bNumber;
            $uniqid = md5(uniqid(microtime(true),true));
            $batch->number = $uniqid;
            $batch->title = $path;
            $batch->save();
//            $settings = Schema::getColumnListing('company_settings');
            $rate = Rate::all()->toArray();
            $reader = Excel::load($path,'UTF-8');
            $reader = $reader->getSheet(0);
            $res = $reader->toArray();
            $company = CompanySetting::find($request->cid);
            $data = [];
            $model = [];
            $is = [];
            foreach ($res as $k=>$i){
                if($k != 0){
                    foreach ($i as $sk=>$si){
                        $is[$this->IntToChr($sk)] = $si;
                    }
                    $model[$k] = $is;
                }
            }
            foreach ($model as $key=>$item){
                $data[$key]['state'] = 1;
                $data[$key]['cid'] = 1;


                if($company->type == 1){
                    if(!empty($company->compulsory_insurance)){
                        $data[$key]['compulsory_insurance'] = $model[$key][$company->compulsory_insurance];
                        if(!empty($request->j_processing_fee_ratio)){
                            $data[$key]['j_service_charge'] = bcmul($data[$key]['compulsory_insurance'],$request->j_processing_fee_ratio,2);
                            $data[$key]['j_application_fee'] = bcmul($data[$key]['j_service_charge'],$rate[1]['rate'],2);
                        }
                    }else{
                        $data[$key]['j_application_fee'] = 0;
                        $data[$key]['j_service_charge'] = 0;
                    }
                    if(!empty($company->commercial_insurance)){
                        $data[$key]['commercial_insurance'] = $model[$key][$company->commercial_insurance];
                        if(!empty($request->s_processing_fee_ratio)){
                            $data[$key]['s_service_charge'] = bcmul($data[$key]['commercial_insurance'],$request->s_processing_fee_ratio,2);
                            $data[$key]['s_application_fee'] = bcmul($data[$key]['s_service_charge'],$rate[2]['rate'],2);
                        }
                    }else{
                        $data[$key]['s_application_fee'] = 0;
                        $data[$key]['s_service_charge'] = 0;
                    }
                    if(!empty($company->vehicles_vessels)){
                        $data[$key]['vehicles_vessels'] = $model[$key][$company->vehicles_vessels];
                        $data[$key]['c_application_fee'] = bcmul($data[$key]['vehicles_vessels'],$rate[0]['rate'],2);
                    }else{
                        $data[$key]['c_application_fee'] = 0;
                        $data[$key]['vehicles_vessels'] = 0;
                    }
                }else{
                    if(!empty($company->vehicles_vessels)){
                        $data[$key]['vehicles_vessels'] = $model[$key][$company->vehicles_vessels];
                        $data[$key]['c_application_fee'] = bcmul($data[$key]['vehicles_vessels'],$rate[0]['rate'],2);
                        if(!empty($company->written_premium)){
                            $data[$key]['compulsory_insurance'] = $model[$key][$company->written_premium];
                            if(!empty($request->j_processing_fee_ratio)){
                                $data[$key]['j_service_charge'] = bcmul($data[$key]['compulsory_insurance'],$request->j_processing_fee_ratio,2);
                                $data[$key]['j_application_fee'] = bcmul($data[$key]['j_service_charge'],$rate[1]['rate'],2);
                            }
                        }else{
                            $data[$key]['compulsory_insurance'] = 0;
                            $data[$key]['j_service_charge'] = 0;
                            $data[$key]['j_application_fee'] = 0;
                        }
                    }else{
                        $data[$key]['c_application_fee'] = 0;
                        $data[$key]['vehicles_vessels'] = 0;
                        if(!empty($company->written_premium)){
                            $data[$key]['commercial_insurance'] = $model[$key][$company->written_premium];
                            if(!empty($request->s_processing_fee_ratio)){
                                $data[$key]['s_service_charge'] = bcmul($data[$key]['compulsory_insurance'],$request->j_processing_fee_ratio,2);
                                $data[$key]['s_application_fee'] = bcmul($data[$key]['s_service_charge'],$rate[2]['rate'],2);
                            }
                        }else{
                            $data[$key]['commercial_insurance'] = 0;
                            $data[$key]['s_service_charge'] = 0;
                            $data[$key]['s_application_fee'] = 0;
                        }
                    }
                }

                $data[$key]['cname'] = $company->title;
                $data[$key]['bid'] = $uniqid;
                $data[$key]['created_at'] = date('Y-m-d H:i:s');
                $data[$key]['updated_at'] = date('Y-m-d H:i:s');
                $data[$key]['number'] = $model[$key][$company->number];
                $data[$key]['insured'] = $model[$key][$company->insured];
                $data[$key]['policy_holder'] = $model[$key][$company->policy_holder];
                $data[$key]['license_plate_number'] = $model[$key][$company->license_plate_number];
                $data[$key]['j_processing_fee_ratio'] = $request->j_processing_fee_ratio;
                $data[$key]['s_processing_fee_ratio'] = $request->s_processing_fee_ratio;
                $data[$key]['total_cost'] = bcadd($data[$key]['s_application_fee'],$data[$key]['c_application_fee'],2);
                $data[$key]['total_cost'] = bcadd($data[$key]['j_application_fee'],$data[$key]['total_cost'],2);
            }
            DB::table('premium_ratios')->insert($data);
//            premiumRatio::create($data);
            return $this->returnInfoAjax('ok!',$data,200);
        }
    }
    public function getList(Request $request){
        $bid = $request->bid;
        $list = premiumRatio::where('state','=',1)->where('bid','=',$bid)->get();
        return json_encode($list);
    }
    function returnInfoAjax($info,$data=[],$status = 1){
        $data = [
            'info'=>$info,
            'data'=>$data,
            'status'=>$status
        ];
        return json_encode($data);
    }
    public function IntToChr($index, $start = 65) {
        $str = '';
        if (floor($index / 26) > 0) {
            $str .= $this->IntToChr(floor($index / 26)-1);
        }
        return $str . chr($index % 26 + $start);
    }
    public function listInfo(Request $request){
        return view('Home.listInfo');
    }
    public function getInfoList(){
        $list = premiumRatio::join('company_settings','company_settings.id','=','premium_ratios.cid')->select('premium_ratios.*','company_settings.title as cname')->get();
        return json_encode($list);
    }
    public function version_user($data){
        $arr = [
            'name' => $data['name'],
            'password' => $data['password']
        ];
        $arr1 = [
            'email' => $data['name'],
            'password' => $data['password']
        ];
        if(Auth::attempt($arr) || Auth::attempt($arr1)){
            return true;
        }else{
            return false;
        }
    }
}
